﻿using AiQiuQuan.Sport.Core.AspNetCore;
using AiQiuQuan.Sport.Model;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Text;

namespace AiQiuQuan.Sport.WebApi.Core
{
    /// <summary>
    /// 结合老项目授权认证
    /// </summary>
    public static class AuthenticationServiceExtensions
    {
        /// <summary>
        /// 结合老项目授权验证；token生成在老项目
        /// </summary>
        public static IServiceCollection AddCorpAuthentication(this IServiceCollection services, IConfiguration configuration)
        {
            services.Configure<JwtOption>(configuration.GetSection("JwtOptions"));
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            services.AddAuthentication()
                .AddScheme<AuthenticationSchemeOptions, SimpleAuthHandler>("PcAuth", null)
                .AddJwtBearer("Bearer", delegate (JwtBearerOptions options)
                {
                    options.Events = new JwtBearerEvents
                    {
                        OnMessageReceived = (context) =>
                        {
                            var token = context.Request.Headers["Authorization"];
                            if (string.IsNullOrWhiteSpace(token) || !token.ToString().StartsWith("Bearer "))
                            {
                                context.Token = context.Request.Query["t"];
                            }

                            return Task.CompletedTask;
                        }
                    };
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        NameClaimType = "name",
                        RoleClaimType = "role",
                        ValidateIssuer = true,
                        ClockSkew = TimeSpan.FromSeconds(0),
                        ValidIssuer = configuration["JwtOptions:Issuer"],
                        ValidateAudience = true,
                        ValidAudience = configuration["JwtOptions:Audience"],
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JwtOptions:SecurityKey"])),
                        ValidateLifetime = true
                    };
                });
            return services;
        }
    }
}
